package com.iwhalecloud.bss.kite.cucc.service.listener;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IGreenWayOrderService;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalErrorConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.greenWayOrder.LocalGreenWayOrderService;
import com.iwhalecloud.bss.kite.cucc.service.even.BeforeSceneReCommitEvent;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstContract;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.scene.service.query.QueryOfferInstContractService;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName : BeforeSceneReCommitEventListener
 * @Description : 重提场景提交前事件监听器
 */
@Service
@Component
public class BeforeSceneReCommitEventListener {

    @Resource
    private IQuerySceneInstService querySceneInstService;

    @EventListener
    @Order(1)
    public void checkStartRentTimeAndStopRentTime (BeforeSceneReCommitEvent beforeSceneCommitEvent) {
        String sceneInstId = beforeSceneCommitEvent.getSceneInstId();
        String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
        KiteAttr startRentTImeAttr = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, "REC_10057", "203");
        KiteAttr stopRentTimeAttr = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, "REC10033", "207");
        // OrderStartRentIntSDHV：国际产品的编码
        if("OrderStartRent".equalsIgnoreCase(taskCode) || "OrderStartRentIntSDHV".equalsIgnoreCase(taskCode)) {
            if(StringUtils.isBlank(startRentTImeAttr.getValue())) {
                LocalErrorConsts.ATTR_NOT_NULL.throwOut("起租时间");
            }
        } else if ("OrderStopRent".equalsIgnoreCase(taskCode) || "OrderStopRentIntSDHV".equalsIgnoreCase(taskCode)) {
            if(StringUtils.isBlank(stopRentTimeAttr.getValue())) {
                LocalErrorConsts.ATTR_NOT_NULL.throwOut("止租时间");
            }
        }
    }

    /**
     * 绿色工单校验
     * @param beforeSceneCommitEvent
     */
    @EventListener
    @Order(2)
    public void greenWayOrderCheck(BeforeSceneReCommitEvent beforeSceneCommitEvent) {
        String sceneInstId = beforeSceneCommitEvent.getSceneInstId();
        String custId = beforeSceneCommitEvent.getCustId();
        String serviceOfferId = beforeSceneCommitEvent.getServiceOfferId();

        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String rootInstId = kiteSceneInst.getRootInstId();

        String cateId = querySceneInstService.getOfferInstAttrValue(custId, rootInstId, "cateId");

        LocalGreenWayOrderService service = SpringUtil.getBean(LocalGreenWayOrderService.class);
        IGreenWayOrderService handler = service.getHandlerByCateId(cateId);
        if (Objects.nonNull(handler)) {
            handler.check(sceneInstId, custId);
        }
    }

    /**
     * 合同信息校验
     *
     * @param beforeSceneCommitEvent
     */
    @EventListener
    @Order(3)
    public void checkContractInfo(BeforeSceneReCommitEvent beforeSceneCommitEvent) {
        String serviceOfferId = beforeSceneCommitEvent.getServiceOfferId();
        if (KiteStringUtils.equals(serviceOfferId, LocalServiceOfferConsts.PAY_RELATION_MANAGMENT)) {
            return;
        }
        String sceneInstId = beforeSceneCommitEvent.getSceneInstId();
        List<KiteOfferInst> mainOfferInsts = this.querySceneInstService.listMainOfferInsts(sceneInstId);
        QueryOfferInstContractService queryOfferInstContractService = SpringUtil.getBean(QueryOfferInstContractService.class);
        // 合同
        List<KiteOfferInstContract> kiteOfferInstContracts = new ArrayList<>();
        if (!KiteListUtils.isEmpty(mainOfferInsts)) {
            for (KiteOfferInst offerInst : mainOfferInsts) {
                kiteOfferInstContracts.addAll(queryOfferInstContractService
                    .listOfferInstContracts(beforeSceneCommitEvent.getCustId(), offerInst.getOfferInstId()));
            }
        }
        kiteOfferInstContracts.removeIf(kiteOfferInstContract -> ActionType.X.name().equals(kiteOfferInstContract.getActionType().name()));

        kiteOfferInstContracts = kiteOfferInstContracts.stream()
            .filter(contract -> !KiteStringUtils.equalsAny(contract.getActionType().name(),ActionType.X.name(),ActionType.D.name()))
            .collect(Collectors.toList());
        kiteOfferInstContracts.forEach(offerInstContractRel -> {
            if (KiteStringUtils.isEmpty(offerInstContractRel.getContractType())) {
                BssException.throwOut(KeyConsts.LOG_MODULE, "","当前合同缺少合同类型，请更换合同或重新上传合同");
            }
        });
    }
}
